package com.example.administrator.text;

import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import util.BitmapUtil;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.NetUtils;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import view.RoundImageView;
import view.diaLogView.CrowdRetunDialog;
import view.diaLogView.RetunDialog;
import view.diaLogView.UploadDialog;

/**
 * 授权手机和pc联网
 */
public class AuthorizationActivity extends BaseActivity {
    public static final String TYPE = "PHONE";
    private String mType,mSessionId,mToken,mID,mBand;  //类型
    private String url = "";
    private UploadDialog mUploadDialog;

    @Bind(R.id.enter_accountlist)             FrameLayout mFrameLayout;
    @Bind(R.id.linear_authorization_he)       LinearLayout mLinearAHe;            //PC授权别人
    @Bind(R.id.linear_authorization_own)      LinearLayout mLinearAOwn;          //PC授权自己
    @Bind(R.id.linear_authorization_phoneown) LinearLayout mLinearAPhoneown;    //手机授权
    @Bind(R.id.iv_authorization_phonehead)    RoundImageView mIvAuthorPhoneHead;    //头像
    @Bind(R.id.tv_authorization_phonename)    TextView     mTvAuthorPhoneName;   //姓名
    @Bind(R.id.tv_authorization_phone)        TextView     mTvAuthorPhone;      //手机
    @Bind(R.id.tv_authorization_phonehint)    TextView     mTvAuthorPhoneHint; //提示
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_authorization);
        ButterKnife.bind(this);
        init();

    }

    private void init() {
        mType = getIntent().getStringExtra("type");
        mSessionId = getIntent().getStringExtra("sessionid");
        mID = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mUseridDB, "");
        HomeUtil.getHemeUtilNew().getStatusBar(this,mFrameLayout);
        mToken = (String) SharedPreferencesUtils.getParam(AuthorizationActivity.this, HomeUtil.mTokenDB, "");
        if (mType.equals(TYPE)){
            mLinearAHe.setVisibility(View.GONE);
            mLinearAOwn.setVisibility(View.GONE);
            mLinearAPhoneown.setVisibility(View.VISIBLE);
            initData();
        }else {
            mLinearAHe.setVisibility(View.GONE);
            mLinearAOwn.setVisibility(View.VISIBLE);
            mLinearAPhoneown.setVisibility(View.GONE);
        }
    }

    /**
     * 返回
     */
    @OnClick(R.id.image_authorization)
    void Return(){
      finish();
    }

    /**
     * 手机授权OK
     */
    @OnClick(R.id.text_authorization_ok)
    void phoneOk(){
        getPhoneAccreditNet();
    }

    /**
     * pc授权自己OK
     */
    @OnClick(R.id.linear_authorization_own)
    void pcOwn(){
        getPcOneselfAccreditNet();
    }

    /**
     * pc授权他人OK
     */
    @OnClick(R.id.linear_authorization_he)
    void pcHe(){
        getPcOthersfAccreditNet();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mBand = "";
        mUploadDialog = new UploadDialog(this,"加载中");
        mUploadDialog.show();
        HashMap<String, Object> map = new HashMap<>();
        map.put("sessionid",mSessionId);
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngAccredit_infoNetQr,stringJson,mToken,mID,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mID,Url.mStirngAccredit_infoNetQr,stirngSign,time);
        LogUtil.eE("",MyApplication.getApp().getFWQString()+"    "+mSessionId);
        if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
            url = Url.getUrlNew().getAppIP();
        }else {
            url = MyApplication.getApp().getFWQString();
        }
        getLogger().info("initData---->手机扫手机 信息显示 url "+url+"sessionid"+mSessionId+"band"+mBand+"...NF_callid..."+map1.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(this,url,1,map1,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    LogUtil.eE("",response);
                    getLogger().info("initData---->onSuccess()--->"+response);
                    mUploadDialog.dismiss();
                    if(json.getInt("code") == 1){
                        String phone = json.getString("phone");
                        String nickname = json.getString("nickname");
                        String head = json.getString("headimg");
                        String netTime ="请求您授权上网";
                        mBand = json.getString("band");
                        mTvAuthorPhoneName.setText(nickname);
                        mTvAuthorPhone.setText(phone);
                        if(Double.parseDouble(json.getString("netTime"))>1){
                            netTime = netTime+json.getString("netTime")+"小时";
                        }else {
                            netTime = netTime+Double.parseDouble(json.getString("netTime"))*60+"分钟";
                        }

                        mTvAuthorPhoneHint.setText(netTime);
                        BitmapUtil.newBitmap().showBitmap(AuthorizationActivity.this,head,mIvAuthorPhoneHead,R.mipmap.weaccount_head,null);

                    }else if(json.getInt("code") == 0){
                        if(json.getInt("reason") == 1){
                          mTvAuthorPhoneName.setText("授权联网");
                          mTvAuthorPhoneHint.setText("二维码失效");
                        }else if(json.getInt("reason") == 2){
                          mTvAuthorPhoneName.setText("授权联网");
                          mTvAuthorPhoneHint.setText("您没有权限授权他人联网");
                        }
                    }else if(json.getInt("code") == -1){
                        Toast.makeText(AuthorizationActivity.this,getString(R.string.FWQ),Toast.LENGTH_SHORT).show();
                    }else if (json.getInt("code") == -2) {
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(AuthorizationActivity.this);
                        crowdRetunDialog.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override public void onFailure(Throwable error) {
                mUploadDialog.dismiss();
                StringUtil.getStringUtilNew().getExceptionCode(AuthorizationActivity.this,error.toString());
            }
        });
    }


    /**
     * 手机的授权上网
     */
    private void getPhoneAccreditNet(){
        if(mBand.equals("")){
            return;
        }
        mUploadDialog = new UploadDialog(this,"授权中");
        mUploadDialog.show();

        HashMap<String, Object> map = new HashMap<>();
        map.put("sessionid",mSessionId);
        map.put("band",mBand);
        mMap.put("callid",StringUtil.getStringUtilNew().getRandom());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngAccredit_verifyNetQr,stringJson,mToken,mID,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mID,Url.mStirngAccredit_verifyNetQr,stirngSign,time);
        if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
            url = Url.getUrlNew().getAppIP();
        }else {
            url = MyApplication.getApp().getFWQString();
        }
        getLogger().info("getPhoneAccreditNet---->手机权限手机url "+url+"sessionid"+mSessionId+"band"+mBand+"...NF_callid..."+map1.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(this,url,1,map1, new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    LogUtil.eE("",response);
                    getLogger().info("getPhoneAccreditNet---->onSuccess()-->String--"+response);
                    mUploadDialog.dismiss();
                    if(json.getInt("code") == 1){
                        if(json.getInt("connect") == 1){
                            final RetunDialog retunDialog = new RetunDialog(AuthorizationActivity.this,"",6,true);
                            retunDialog.show();
                            HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                                @Override public void run() {
                                    retunDialog.dismiss();
                                    finish();
                                }
                            },1000);
                        }else {
                            if(json.has("msg")){
                                Toast.makeText(AuthorizationActivity.this,json.getString("msg")+"",Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(AuthorizationActivity.this,"授权失败",Toast.LENGTH_SHORT).show();
                            }
                        }

                    }else if (json.getInt("code") == -2) {
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(AuthorizationActivity.this);
                        crowdRetunDialog.show();
                    }else if (json.getInt("code") == 0){
                        if(json.has("msg")){
                            Toast.makeText(AuthorizationActivity.this,json.getString("msg")+"",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(AuthorizationActivity.this,"授权失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                    else if(json.getInt("code") == -1){
                        Toast.makeText(AuthorizationActivity.this,getString(R.string.FWQ),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override public void onFailure(Throwable error) {
                mUploadDialog.dismiss();
                StringUtil.getStringUtilNew().getExceptionCode(AuthorizationActivity.this,error.toString());
            }
        });
    }

    /**
     * pc端自己联网
     */
    private void getPcOneselfAccreditNet(){
        mUploadDialog = new UploadDialog(this,"授权中");
        mUploadDialog.show();
        HashMap<String, Object> map = new HashMap<>();
        map.put("sessionid",mSessionId);
        map.put("userid",mID);
        mMap.put("callid",StringUtil.getStringUtilNew().getRandom());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngpcNetQr_pcQrselfNet,stringJson,mToken,mID,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mID,Url.mStirngpcNetQr_pcQrselfNet,stirngSign,time);
        if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
            url = Url.getUrlNew().getAppIP();
        }else {
            url = MyApplication.getApp().getFWQString();
        }
        getLogger().info("getPcOneselfAccreditNet()--->pc授权自己--fwq--"+url+"stirngSign"+stirngSign+"...NF_callid..."+map1.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(this,url,1,map1,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    getLogger().info("getPcOneselfAccreditNet()--->onSuccess()--String"+response);
                    JSONObject json = new JSONObject(response);
                    LogUtil.eE("",response);
                    mUploadDialog.dismiss();
                    if(json.getInt("code") == 1){
                        if(json.getInt("connect") == 1){
                            final RetunDialog retunDialog = new RetunDialog(AuthorizationActivity.this,"",6,true);
                            retunDialog.show();
                            HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                                @Override public void run() {
                                    retunDialog.dismiss();
                                    finish();
                                }
                            },1000);
                        }else {
                            if(json.has("msg")){
                                Toast.makeText(AuthorizationActivity.this,json.getString("msg")+"",Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(AuthorizationActivity.this,"授权失败",Toast.LENGTH_SHORT).show();
                            }
                        }

                    }else if (json.getInt("code") == -2) {
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(AuthorizationActivity.this);
                        crowdRetunDialog.show();
                    } else if (json.getInt("code") == 0){
                        if(json.has("msg")){
                            Toast.makeText(AuthorizationActivity.this,json.getString("msg")+"",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(AuthorizationActivity.this,"授权失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                    else if(json.getInt("code") == -1){
                        Toast.makeText(AuthorizationActivity.this,getString(R.string.FWQ),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override public void onFailure(Throwable error) {
                mUploadDialog.dismiss();
                StringUtil.getStringUtilNew().getExceptionCode(AuthorizationActivity.this,error.toString());
            }
        });
    }

    /**
     * pc端他人联网
     */
    private void getPcOthersfAccreditNet(){

        mUploadDialog = new UploadDialog(this,"授权中");
        mUploadDialog.show();
        HashMap<String, Object> map = new HashMap<>();
        map.put("sessionid",mSessionId);
        map.put("userid",mID);
        mMap.put("callid",StringUtil.getStringUtilNew().getRandom());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngpcNetQr_pcQrotherNet,stringJson,mToken,mID,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mID,Url.mStirngpcNetQr_pcQrotherNet,stirngSign,time);
        if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
            url = Url.getUrlNew().getAppIP();
        }else {
            url = MyApplication.getApp().getFWQString();
        }
        getLogger().info("getPcOthersfAccreditNet()--->pc授权他人--fwq--"+url+"stirngSign"+stirngSign+"...NF_callid..."+map1.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(this,url,1,map1, new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    getLogger().info("getPcOthersfAccreditNet()--->onSuccess--"+response);
                    JSONObject json = new JSONObject(response);
                    mUploadDialog.dismiss();
                    LogUtil.eE("",response);
                    if(json.getInt("code") == 1){
                        if(json.getInt("connect") == 1){
                            final RetunDialog retunDialog = new RetunDialog(AuthorizationActivity.this,"",6,true);
                            retunDialog.show();
                            HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                                @Override public void run() {
                                    retunDialog.dismiss();
                                    finish();
                                }
                            },1000);
                        }else {
                            if(json.has("msg")){
                                Toast.makeText(AuthorizationActivity.this,json.getString("msg")+"",Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(AuthorizationActivity.this,"授权失败",Toast.LENGTH_SHORT).show();
                            }
                        }
                    }else if (json.getInt("code") == -2) {
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(AuthorizationActivity.this);
                        crowdRetunDialog.show();
                    }else if (json.getInt("code") == 0){
                        if(json.has("msg")){
                            Toast.makeText(AuthorizationActivity.this,json.getString("msg")+"",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(AuthorizationActivity.this,"授权失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                    else if(json.getInt("code") == -1){
                        Toast.makeText(AuthorizationActivity.this,getString(R.string.FWQ),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override public void onFailure(Throwable error) {
                mUploadDialog.dismiss();
                StringUtil.getStringUtilNew().getExceptionCode(AuthorizationActivity.this,error.toString());
            }
        });
    }
}
